﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;

namespace Deepcode.ValidationSample.Controllers
{
	[AttributeUsage( AttributeTargets.Property )]
	public class SpecialAuthorNameAttribute : ValidationAttribute
	{
		public string ServerSideName{ get; set; }
		public string ClientSideName{ get; set; }

		public override bool IsValid(object value)
		{
			if( Equals(value, ServerSideName) ) return false;
			return true;
		}
	}

	/// <summary>
	/// This is the client adaptor for the above validation attribute - this outputs the necessary information to our client side
	/// code to trigger validation.
	/// </summary>
	public class SpecialAuthorNameAttributeAdaptor : DataAnnotationsModelValidator<SpecialAuthorNameAttribute>
	{
		private readonly string _clientName;
		private readonly string _message;

		public SpecialAuthorNameAttributeAdaptor( ModelMetadata metadata, ControllerContext context, SpecialAuthorNameAttribute attribute ) : base(metadata, context, attribute)
		{
			_clientName = attribute.ClientSideName;
			_message = attribute.ErrorMessage;
		}

		public override IEnumerable<ModelClientValidationRule> GetClientValidationRules()
		{
			var rule = new ModelClientValidationRule
			{
				ErrorMessage = _message,
				ValidationType = "special-author-check"
			};
			
			rule.ValidationParameters.Add("name", _clientName);

			return new[] { rule };
		}
	}
}